import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../constants.dart';
import '../../../theme.dart';
import 'logic.dart';

class ExpensePage extends StatelessWidget {
  ExpensePage({Key? key}) : super(key: key);

  final ExpenseLogic logic = Get.put(ExpenseLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('支出'),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            size: 16.w,
          ),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Obx(
        () => logic.isLoading.value
            ? const Center(child: CircularProgressIndicator())
            : ListView(
                children: [
                  SizedBox(height: kSpaceMedium),
                  _buildAmount(),
                  SizedBox(height: 20.w),
                  _buildBarChart(),
                  SizedBox(height: 20.w),
                  _buildLineChart(),
                  SizedBox(height: 20.w),
                ],
              ),
      ),
    );
  }

  Widget _buildLineChart() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 10.w),
      child: Obx(
        () => Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '同比环比',
                  style: TextStyle(
                    fontSize: kFontSizeMedium,
                    fontWeight: AppFont.fontMedium,
                    color: AppColor.colorFontBlack,
                  ),
                ),
                Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: AppColor.colorFontLabelGrey,
                      width: 0.5.w,
                    ),
                    borderRadius: BorderRadius.circular(28.w),
                  ),
                  padding: EdgeInsets.only(
                    left: 10.w,
                    right: 4.w,
                  ),
                  height: 28.w,
                  child: DropdownButton(
                    value: logic.year.value,
                    items: logic.yearList.map((year) {
                      return DropdownMenuItem(
                        value: year,
                        child: Text(
                          year,
                          style: TextStyle(
                              fontSize: kFontSizeMini,
                              color: AppColor.colorFontBlack,
                              height: 1.4),
                        ),
                      );
                    }).toList(),
                    onChanged: (value) {
                      logic.onYearChange(value!);
                    },
                    underline: Container(),
                    style: TextStyle(
                      fontSize: kFontSizeMini,
                      color: AppColor.colorFontBlack,
                    ),
                    icon: const Icon(Icons.keyboard_arrow_down),
                  ),
                ),
              ],
            ),
            SizedBox(height: kSpaceMedium),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: List.generate(3, (index) {
                return Container(
                  width: 100.w,
                  padding: EdgeInsets.symmetric(
                    vertical: kSpaceMini,
                    horizontal: kSpaceTiny,
                  ),
                  decoration: BoxDecoration(
                    color: AppColor.colorRectangleGrey,
                    borderRadius: BorderRadius.circular(kRadiusMini),
                  ),
                  child: Column(
                    children: [
                      Text(
                        index == 0
                            ? logic.statisticsInfo.value.curMonth!
                                    .expendMonthRate ??
                                ''
                            : index == 1
                                ? logic.statisticsInfo.value.curMonth!
                                        .expendYearRate ??
                                    ''
                                : logic.statisticsInfo.value.lastMonth!
                                        .expendMonthRate ??
                                    '',
                        style: TextStyle(
                          fontSize: kFontSizeMini,
                          color: AppColor.colorFontBlack,
                        ),
                      ),
                      Text(
                        index == 0
                            ? '本月环比'
                            : index == 1
                                ? '本月同比'
                                : '上月环比',
                        style: TextStyle(
                          fontSize: kFontSizeTiny,
                          color: AppColor.colorFontGrey,
                        ),
                      )
                    ],
                  ),
                );
              }),
            ),
            SizedBox(height: kSpaceMedium),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: List.generate(3, (index) {
                return Container(
                  width: 100.w,
                  padding: EdgeInsets.symmetric(
                    vertical: kSpaceMini,
                    horizontal: kSpaceTiny,
                  ),
                  decoration: BoxDecoration(
                    color: index == 2
                        ? Colors.transparent
                        : AppColor.colorRectangleGrey,
                    borderRadius: BorderRadius.circular(kRadiusMini),
                  ),
                  child: index == 2
                      ? Container()
                      : Column(
                          children: [
                            Text(
                              index == 0
                                  ? logic.statisticsInfo.value.lastMonth!
                                          .expendYearRate ??
                                      ''
                                  : logic.statisticsInfo.value.sumYear!
                                          .expendMonthRate ??
                                      '',
                              style: TextStyle(
                                fontSize: kFontSizeMini,
                                color: AppColor.colorFontBlack,
                              ),
                            ),
                            Text(
                              index == 0 ? '上月同比' : '年累计环比',
                              style: TextStyle(
                                fontSize: kFontSizeTiny,
                                color: AppColor.colorFontGrey,
                              ),
                            )
                          ],
                        ),
                );
              }),
            ),
          ],
        ),
      ),
    );
  }

  /// 创收直方图模块
  Widget _buildBarChart() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 10.w),
      child: Obx(
        () => Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '支出统计',
                  style: TextStyle(
                    fontSize: kFontSizeMedium,
                    fontWeight: AppFont.fontMedium,
                    color: AppColor.colorFontBlack,
                  ),
                ),
                Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: AppColor.colorFontLabelGrey,
                      width: 0.5.w,
                    ),
                    borderRadius: BorderRadius.circular(28.w),
                  ),
                  padding: EdgeInsets.only(
                    left: 10.w,
                    right: 4.w,
                  ),
                  height: 28.w,
                  child: DropdownButton(
                    value: logic.year.value,
                    items: logic.yearList.map((year) {
                      return DropdownMenuItem(
                        value: year,
                        child: Text(
                          year,
                          style: TextStyle(
                              fontSize: kFontSizeMini,
                              color: AppColor.colorFontBlack,
                              height: 1.4),
                        ),
                      );
                    }).toList(),
                    onChanged: (value) {
                      logic.onYearChange(value!);
                    },
                    underline: Container(),
                    style: TextStyle(
                      fontSize: kFontSizeMini,
                      color: AppColor.colorFontBlack,
                    ),
                    icon: const Icon(Icons.keyboard_arrow_down),
                  ),
                ),
              ],
            ),
            SizedBox(height: kSpaceLarge),
            SizedBox(
              height: 240.w,
              child: BarChart(
                BarChartData(
                  titlesData: _barTitlesData,
                  barTouchData: _barTouchData,
                  barGroups: _barGroups,
                  gridData: _gridData,
                  alignment: BarChartAlignment.spaceBetween,
                  borderData: FlBorderData(show: false),
                ),
              ),
            ),
            SizedBox(height: kSpaceMedium),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: List.generate(3, (index) {
                return Container(
                  width: 100.w,
                  padding: EdgeInsets.symmetric(
                    vertical: kSpaceMini,
                    horizontal: kSpaceTiny,
                  ),
                  decoration: BoxDecoration(
                    color: AppColor.colorRectangleGrey,
                    borderRadius: BorderRadius.circular(kRadiusMini),
                  ),
                  child: Column(
                    children: [
                      Text(
                        index == 0
                            ? logic.statisticsInfo.value.curMonth!
                                    .expendTotal ??
                                ''
                            : index == 1
                                ? logic.statisticsInfo.value.lastMonth!
                                        .expendTotal ??
                                    ''
                                : logic.statisticsInfo.value.sumYear!
                                        .expendTotal ??
                                    '',
                        style: TextStyle(
                          fontSize: kFontSizeMini,
                          color: AppColor.colorFontBlack,
                        ),
                      ),
                      Text(
                        index == 0
                            ? '本月支出'
                            : index == 1
                                ? '上月支出'
                                : '年累计支出',
                        style: TextStyle(
                          fontSize: kFontSizeTiny,
                          color: AppColor.colorFontGrey,
                        ),
                      )
                    ],
                  ),
                );
              }),
            ),
          ],
        ),
      ),
    );
  }

  /// 创收累计模块
  Widget _buildAmount() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 10.w),
      padding:
          EdgeInsets.symmetric(vertical: kSpaceMedium, horizontal: kSpaceSmall),
      decoration: BoxDecoration(
        color: AppColor.colorRectangleGrey,
        borderRadius: BorderRadius.circular(kRadiusMedium),
      ),
      child: Column(
        children: [
          Text(
            logic.statisticsInfo.value.expendAmount ?? '',
            style: TextStyle(
              fontSize: kFontSizeLarge,
              fontWeight: AppFont.fontMedium,
              color: AppColor.colorFontBlack,
            ),
          ),
          SizedBox(height: kSpaceTiny),
          Text(
            '总支出累计',
            style: TextStyle(
              fontSize: kFontSizeMini,
              color: AppColor.colorFontGrey,
            ),
          ),
        ],
      ),
    );
  }

  FlGridData get _gridData => FlGridData(
      show: true,
      drawVerticalLine: false,
      getDrawingHorizontalLine: (value) {
        return FlLine(
          color: const Color(0xFFF0F2F6),
          strokeWidth: 0.5.w,
        );
      });

  BarTouchData get _barTouchData => BarTouchData(
      touchTooltipData: BarTouchTooltipData(
        getTooltipColor: (group) {
          return const Color(0xffCFD0DB);
        },
        getTooltipItem: (group, groupIndex, rod, rodIndex) {
          return BarTooltipItem(
            '¥${rod.toY}',
            TextStyle(
              color: AppColor.colorFontBlack,
              fontSize: kFontSizeMini,
            ),
          );
        },
      ),
      touchCallback: (event, barTouchResponse) {
        if (!event.isInterestedForInteractions ||
            barTouchResponse == null ||
            barTouchResponse.spot == null) {
          logic.touchBarIndex.value = null;
          return;
        }
        logic.touchBarIndex.value = barTouchResponse.spot!.touchedBarGroupIndex;
      });

  LineTouchData get _lineTouchData => LineTouchData(
        touchTooltipData: LineTouchTooltipData(
          getTooltipColor: (group) {
            return const Color(0xffCFD0DB);
          },
          getTooltipItems: (List<LineBarSpot> touchedSpots) {
            return touchedSpots.map((LineBarSpot touchedSpot) {
              return LineTooltipItem(
                '${touchedSpot.barIndex == 0 ? '同比' : '环比'}：${(touchedSpot.y * 100).toInt()}%',
                textAlign: TextAlign.start,
                TextStyle(
                  color: AppColor.colorFontBlack,
                  fontSize: kFontSizeMini,
                ),
              );
            }).toList();
          },
        ),
      );

  FlTitlesData get _lineTitlesData => FlTitlesData(
        leftTitles: AxisTitles(
          sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 40,
              getTitlesWidget: (value, meta) {
                return Text(
                  '${(value * 100).toInt()}%',
                  style: TextStyle(
                    fontSize: kFontSizeTiny,
                    color: AppColor.colorFontGrey,
                  ),
                );
              }),
        ),
        topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
        rightTitles:
            const AxisTitles(sideTitles: SideTitles(showTitles: false)),
        bottomTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            getTitlesWidget: (value, meta) {
              List<String> months = [
                '1月',
                '2月',
                '3月',
                '4月',
                '5月',
                '6月',
              ];
              return Text(
                months[value.toInt()],
                style: TextStyle(
                  fontSize: kFontSizeMini,
                  color: AppColor.colorFontBlack,
                ),
              );
            },
          ),
        ),
      );

  // 直方图标题数据
  FlTitlesData get _barTitlesData => FlTitlesData(
        leftTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            reservedSize: 40,
            getTitlesWidget: (value, meta) {
              return Text(
                value.toInt() > 10000
                    ? '${value ~/ 10000}万'
                    : value.toInt().toString(),
                style: TextStyle(
                  fontSize: kFontSizeTiny,
                  color: AppColor.colorFontGrey,
                ),
              );
            },
          ),
        ),
        topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
        rightTitles:
            const AxisTitles(sideTitles: SideTitles(showTitles: false)),
        bottomTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            getTitlesWidget: (value, meta) {
              List<String> months = [
                '1月',
                '2月',
                '3月',
                '4月',
                '5月',
                '6月',
                '7月',
                '8月',
                '9月',
                '10月',
                '11月',
                '12月',
              ];
              return Text(
                months[value.toInt()],
                style: TextStyle(
                  fontSize: kFontSizeTiny,
                  color: AppColor.colorFontBlack,
                ),
              );
            },
          ),
        ),
      );

  List<LineChartBarData> get _lineBarsData => List.generate(2, (index) {
        return LineChartBarData(
          spots: index == 0
              ? List.generate(6, (index) {
                  return FlSpot(
                      index.toDouble(),
                      logic.statisticsInfo.value.expendData!.yearRate![index]
                          .toDouble());
                })
              : List.generate(6, (index) {
                  return FlSpot(
                      index.toDouble(),
                      logic.statisticsInfo.value.expendData!.monthRate![index]
                          .toDouble());
                }),
          isCurved: true,
          preventCurveOverShooting: true,
          color: index == 0 ? const Color(0xFF48A0FF) : const Color(0xFF54D48F),
        );
      });

  List<BarChartGroupData> get _barGroups =>
      List.generate(logic.statisticsInfo.value.expendData!.value!.length,
          (i) {
        return BarChartGroupData(
          x: i,
          barRods: [
            BarChartRodData(
              toY: logic.statisticsInfo.value.expendData!.value![i].toDouble(),
              width: 16.w,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(16),
                topRight: Radius.circular(16),
                bottomRight: Radius.circular(0),
                bottomLeft: Radius.circular(0),
              ),
              gradient: logic.touchBarIndex.value != null &&
                      logic.touchBarIndex.value == i
                  ? const LinearGradient(
                      colors: [Color(0xff505BFF), Color(0xff7786FF)],
                      begin: Alignment.bottomCenter,
                      end: Alignment.topCenter,
                    )
                  : const LinearGradient(
                      colors: [Color(0xff7D86FF), Color(0xffB4BDFF)],
                      begin: Alignment.bottomCenter,
                      end: Alignment.topCenter,
                    ),
            ),
          ],
        );
      });
}
